package unicorns;

import java.util.ArrayList;

import operatingSystems.*;

public class Mother extends Thread{
	
	int lifeTime;
	boolean sleeping;
	ArrayList<Pot>pots;
	Barrier eating;
	Semaphore sleepingMother;
	Semaphore checkPots;
	
	/**
	 * 
	 * @param myPlayGround the playground in which the mother will take care of her children in 
	 */
	
	public Mother(PlayGround myPlayGround){
		
		this.lifeTime = myPlayGround.lifeTime; 
		this.sleeping = true;
		this.eating = myPlayGround.eating;
		this.checkPots = myPlayGround.checkPots;
		this.sleepingMother = myPlayGround.sleepingMother;
		this.pots = myPlayGround.pots;
		
	}
	
	public void run(){
		
		for(int i = 0; i < lifeTime; i++){
			try {
				goToSleep();
				search();
				fillPots();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
		}
		
		System.out.println("Mother = retired.");
		//System.exit(0);
		
	}
	
	/**
	 * this method lets the mother go to sleep by setting the sleeping flag to true 
	 * @throws InterruptedException
	 */
	
	public void goToSleep() throws InterruptedException{
		
		sleeping = true;
		System.out.println("Mother is now going to sleep.");
		sleepingMother.down();
		
	}
	
	/**
	 * this methods keeps the mother occupied for some time just to search for some food 
	 * @throws InterruptedException
	 */
	
	public void search() throws InterruptedException{
		System.out.println("Mother is now searching for food.");
		this.sleep(10);
		
	}
	/**
	 * this method lets the mother fill up the pots when they are empty 
	 * @throws InterruptedException
	 */
	public void fillPots() throws InterruptedException{
		
		checkPots.down();
		fill();
		checkPots.up();
		wakeUpBabies();
		
	}
	/**
	 * this method just wakes up the babies telling them that the food is ready
	 * 
	 * @throws InterruptedException
	 */
	public void wakeUpBabies() throws InterruptedException{
		
		eating.releaseAll();
	
	}
	
	
	/**
	 * this is a helper method for felling up the pots 
	 */
	public void fill(){
		
		System.out.println("Mother is now filling the pots.");
		for(int i = 0; i< pots.size();i++){
			pots.get(i).full=true;
		}
		System.out.println("The Pots are now full");
	}
	
	
	
}
